package com.atguigu.gulimallcart.controller;

import com.atguigu.common.utils.R;
import com.atguigu.gulimallcart.service.CartService;
import com.atguigu.gulimallcart.vo.Cart;
import com.atguigu.gulimallcart.vo.CartItemVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.ExecutionException;

@Controller
public class CartController {

    @Autowired
    CartService cartService;

    /**
     * 查询结算页购物车数据
     */
    @ResponseBody
    @GetMapping( "/orderFeignCart")
    public List<CartItemVo> orderFeignCart(@RequestParam("id") Long id) {
        List<CartItemVo> cartItemVo = cartService.orderFeignCart(id);
        return cartItemVo;
    }

    /**
     * 删除商品信息
     */
    @GetMapping(value = "/deleteItem")
    public String deleteItem(@RequestParam("skuId") Long skuId) {

        cartService.deleteIdCartInfo(skuId);

        return "redirect:http://cart.gulimall.com/cart.html";

    }

    /**
     * 改变商品数量
     */
    @GetMapping(value = "/countItem")
    public String countItem(@RequestParam(value = "skuId") Long skuId,
                            @RequestParam(value = "num") Integer num) {

        cartService.changeItemCount(skuId,num);

        return "redirect:http://cart.gulimall.com/cart.html";
    }

    /**
     * 商品是否选中
     */
    @GetMapping(value = "/checkItem")
    public String checkItem(@RequestParam(value = "skuId") Long skuId,
                            @RequestParam(value = "checked") Integer checked) {
        cartService.checkItem(skuId,checked);

        return "redirect:http://cart.gulimall.com/cart.html";

    }

    /**
     * 购物车展示页
     */
    @GetMapping("/cart.html")
    public String cartList(Model model) throws ExecutionException, InterruptedException {
        Cart cart = cartService.getCart();
        model.addAttribute("cart",cart);
        return "cartList";
    }


    /**
     * 添加商品到购物车
     */
    @GetMapping("/addToCart")
    public String addToCart(@RequestParam("skuId") Long skuId,
                            @RequestParam("num") Integer num) throws ExecutionException, InterruptedException {

        /**
         * 需求：防止刷新页面执行会频繁添加购物车的操作，使用重定向操作，展示数据的页面不执行添加购物车操作，只用来展示数据
         *
         * 问题：怎么将数据传到重定向的页面？ 不用传，再查一次
         */

        cartService.addToCart(skuId,num);
        //addAttribute（）重定向参数拼在url后，addFlashAttribute（）会隐藏参数，参数会放在session中，跳过去就立马删了
        //RedirectAttributes ra  ra.addAttribute("skuId",skuId);
        return "redirect:http://cart.gulimall.com/showCart/" + skuId.toString();
    }


    /**
     * 频繁刷新不会去执行添加操作
     */
    @GetMapping("/showCart/{skuId}")
    public String showCart(Model model, @PathVariable("skuId") Long skuId){
        CartItemVo cartItemVo = cartService.getCartItem(skuId);
        model.addAttribute("cartItem",cartItemVo);
        return "success";
    }


}
